package net.io;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class IntgenServer
{
	public static int DEFAULT_PORT = 1919;
	public static void main(String[] args)
	{
		ServerSocketChannel  serverSocketChannel;
		Selector selector;
		try
		{
			serverSocketChannel = ServerSocketChannel.open();
			ServerSocket ss = serverSocketChannel.socket();
			InetSocketAddress address = new InetSocketAddress(DEFAULT_PORT);
			ss.bind(address);
			serverSocketChannel.configureBlocking(false);
			selector = Selector.open();
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		}
		catch (Exception e)
		{
			return;
		}
		while(true)
		{
			try
			{
				selector.select();
			}
			catch (Exception e)
			{
				break;
			}
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = selectedKeys.iterator();
			while(iterator.hasNext())
			{
				SelectionKey next = iterator.next();
				try
				{
					if(next.isWritable())
					{
						ServerSocketChannel server = (ServerSocketChannel) next.channel();
						SocketChannel client = server.accept();
						client.configureBlocking(false);
						SelectionKey keyTwo = client.register(selector, SelectionKey.OP_WRITE);
						ByteBuffer output = ByteBuffer.allocate(4);
						output.putInt(0);
						output.flip();
						keyTwo.attach(output);
					}else if(next.isAcceptable())
					{
						SocketChannel client = (SocketChannel) next.channel();
						ByteBuffer output = (ByteBuffer) next.attachment();
						if(!output.hasRemaining())
						{
							output.rewind();
							int value = output.getInt();
							output.clear();
							output.putInt(value+1);
							output.flip();
						}
						client.write(output);
					}
				}
				catch (Exception e)
				{
					next.cancel();
					try
					{
						next.channel().close();
					}
					catch (Exception e2)
					{
					}
				}
			}
		}
	}
}
